﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Interop;
using PGun.WindowsInput;
using Encoder = System.Text.Encoder;

namespace HangameAuto01
{
    public partial class CaptureForm : Form
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);


        private IntPtr ptrHangame;

        public CaptureForm()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            
         
            Random rnd = new Random();
            while (!e.Cancel)
            {
                if (this.backgroundWorker1.CancellationPending)
                    e.Cancel = true;
                Thread.Sleep(200);
                this.backgroundWorker1.ReportProgress(rnd.Next(10000));
            }
            
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

            Point curPos = new Point(Cursor.Position.X, Cursor.Position.Y);
            Size curSize = new Size();
            curSize.Height = Cursor.Current.Size.Height;
            curSize.Width = Cursor.Current.Size.Width;

            this.TopMost = false;

            Rectangle bounds = Screen.GetBounds(Screen.GetBounds(Point.Empty));

            this.pictureBox1.InitialImage = null;
            CaptureImage(false, curSize, curPos, Point.Empty, Point.Empty, bounds);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if(!this.backgroundWorker1.IsBusy)
            this.backgroundWorker1.RunWorkerAsync();
        }

        public void CaptureImage(bool showCursor, Size curSize, Point curPos, Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle)
        {
            //this.ptrHangame = new IntPtr(2033446);
            if (this.ptrHangame == IntPtr.Zero)
            {
                foreach (Process process in Process.GetProcesses())
                {
                    
                    if (process.MainModule.ModuleName == ("poker7.exe"))
                    {
                        process.Refresh();
                        this.ptrHangame = process.MainWindowHandle;
                        
                        break;
                        
                    }
                   
                }
            }

            if (this.ptrHangame == IntPtr.Zero)
            {
                MessageBox.Show("한게임이 실행중이 아닙니다.");
                this.backgroundWorker1.CancelAsync();
                return;
            }

            RECT rect = new RECT();
            SetForegroundWindow(this.ptrHangame);
            if (GetWindowRect(this.ptrHangame, ref rect))
            {
                Size size = new Size(rect.Right - rect.Left,
                                     rect.Bottom - rect.Top);
                // Get information about the screen
                using (Graphics browserGraphics = Graphics.FromHwnd(this.ptrHangame))
                {
                    // apply that info to a bitmap...
                    Bitmap screenshot = new Bitmap(size.Width, size.Height,
                                                   browserGraphics);
                        // and create an Graphics to manipulate that bitmap.
                        using (Graphics imageGraphics = Graphics.FromImage(screenshot))
                        {
                            int hWndX = rect.Left;
                            int hWndY = rect.Top;

                            imageGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            imageGraphics.SmoothingMode = SmoothingMode.HighQuality;
                            imageGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            imageGraphics.CompositingQuality = CompositingQuality.HighQuality;

                            imageGraphics.CopyFromScreen(hWndX, hWndY, 0, 0, size);

                            MethodInvoker wrapper = new MethodInvoker(delegate()
                                {
                                    this.pictureBox1.Image = screenshot;
                                    this.pictureBox1.Image.Save(@"c:\image" + DateTime.Now.ToString("yyyyMMddhhss") + ".bmp");
                                });
                            if (this.InvokeRequired)
                                this.Invoke(wrapper);
                            else
                                wrapper();


                        }
                    
                }
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            RECT rect = new RECT();
            if (GetWindowRect(this.ptrHangame, ref rect))
            {
                InputSimulator input = new InputSimulator();
                int x = rect.Left + 400;
                int y = rect.Top + 70;
                input.Mouse.MoveMouseTo(Convert.ToDouble(x) / Screen.PrimaryScreen.Bounds.Width * 65535, Convert.ToDouble(y) / Screen.PrimaryScreen.Bounds.Height * 65535);
                input.Mouse.LeftButtonClick();
            }
            
        }

        private void button4_Click(object sender, EventArgs e)
        { 
            RECT rect = new RECT();

            Bitmap imgCurrent = GetHangameImage();

            if (GetWindowRect(this.ptrHangame, ref rect))
            {
                Color curColor = imgCurrent.GetPixel(rect.Left + 292, rect.Top + 167);
                double[] current = GetInputPoint(MousePosition.X, MousePosition.Y);
                double[] refresh = GetInputPoint(rect.Left + 419, rect.Top + 129);
                double[] room1In = GetInputPoint(rect.Left + 477, rect.Top + 174);
                InputSimulator input = new InputSimulator();

                bool bIn = false;
                while (!bIn)
                {
                    
                    input.Mouse.MoveMouseTo(refresh[0], refresh[1]);
                    input.Mouse.LeftButtonClick();
                    Thread.Sleep(200);

                    input.Mouse.MoveMouseTo(room1In[0], room1In[1]);
                    input.Mouse.LeftButtonClick();

                    Thread.Sleep(1300);
                    Color color2 = GetHangameImage().GetPixel(rect.Left + 292, rect.Top + 167);
                    if (curColor != color2)
                        bIn = true;
                }
                input.Mouse.MoveMouseTo(current[0], current[1]);
            }
        }

        private double[] GetInputPoint(int pX,int pY)
        {
            return new double[] { Convert.ToDouble(pX) / Screen.PrimaryScreen.Bounds.Width * 65535, Convert.ToDouble(pY) / Screen.PrimaryScreen.Bounds.Height * 65535 };
        }


        private Bitmap GetHangameImage()
        {
            Bitmap screenshot;

            //this.ptrHangame = new IntPtr(2033446);
            if (this.ptrHangame == IntPtr.Zero)
            {
                foreach (Process process in Process.GetProcesses())
                {

                    if (process.MainModule.ModuleName == ("poker7.exe"))
                    {
                        process.Refresh();
                        this.ptrHangame = process.MainWindowHandle;

                        break;

                    }

                }
            }


            RECT rect = new RECT();
            SetForegroundWindow(this.ptrHangame);
            if (GetWindowRect(this.ptrHangame, ref rect))
            {
                Size size = new Size(rect.Right - rect.Left,
                                     rect.Bottom - rect.Top);
                // Get information about the screen
                using (Graphics browserGraphics = Graphics.FromHwnd(this.ptrHangame))
                {
                    // apply that info to a bitmap...
                    screenshot = new Bitmap(size.Width, size.Height,
                                                   browserGraphics);
                    // and create an Graphics to manipulate that bitmap.
                    using (Graphics imageGraphics = Graphics.FromImage(screenshot))
                    {
                        int hWndX = rect.Left;
                        int hWndY = rect.Top;

                        imageGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        imageGraphics.SmoothingMode = SmoothingMode.HighQuality;
                        imageGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        imageGraphics.CompositingQuality = CompositingQuality.HighQuality;

                        imageGraphics.CopyFromScreen(hWndX, hWndY, 0, 0, size);


                        return screenshot;

                    }

                }
            }

            return null;
        }
        
    }
}
